package com.cssy.xxkj.logic.web;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONArray;
import com.cssy.base.web.BaseController;
import com.cssy.base.web.BodyMsg;
import com.cssy.xxkj.basic.entity.BasicCompanyTestDO;
import com.cssy.xxkj.basic.entity.BasicCurrencyTestDO;
import com.cssy.xxkj.basic.entity.BasicModePaymentTestDO;
import com.cssy.xxkj.basic.service.IBasicUtilService;
import com.cssy.xxkj.logic.contants.BillStatusUtil;
import com.cssy.xxkj.logic.entity.LogicPayReturnDO;
import com.cssy.xxkj.logic.entity.LogicPayReturnItemDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseReturnDO;
import com.cssy.xxkj.logic.entity.LogicPurchaseReturnItemDO;
import com.cssy.xxkj.logic.service.ILogicPayReturnService;
import com.cssy.xxkj.logic.service.ILogicPurchaseReturnItemService;
import com.cssy.xxkj.logic.service.ILogicPurchaseReturnService;
import com.cssy.xxkj.logic.service.ILogicPurchaseService;
import com.cssy.xxkj.logic.service.ILogicUtilService;
import com.plat.exception.SyBaseException;
import com.plat.helper.JqGridHandler;
import com.plat.helper.SearchCondition;
import com.plat.helper.SearchConditions;
import com.plat.helper.SearchResult;
import com.plat.util.GlobalResLoader;
import com.plat.util.OperationFlag;
import com.plat.util.json.AjaxUtil;
import com.plat.util.json.OutJsonGrid;

/**
 * 
 * 付款退款controller
 * @author zeyong.gui
 * 
 */
@Controller
@RequestMapping("/logic/paymoneyreturn")
public class PayMoneyReturnController extends BaseController<LogicPayReturnDO> {

	private static final String MANAGER = "/xxkj/logic/paymoneyreturn/PayMoneyReturnManager";// 列表页面
	private static final String EIDT = "/xxkj/logic/paymoneyreturn/PayMoneyReturnOperation";// 添加、修改、显示页面
	
	@Resource(name="logicPayReturnService")
	private ILogicPayReturnService logicPayReturnService;
	
	@Resource(name = "logicPurchaseService")
	private ILogicPurchaseService logicPurchaseService;
	
	@Resource(name = "logicPurchaseReturnService")
	private ILogicPurchaseReturnService logicPurchaseReturnService;
	
	@Resource(name = "logicPurchaseReturnItemService")
	private ILogicPurchaseReturnItemService logicPurchaseReturnItemService;
	
	@Resource(name = "basicUtilService")
	private IBasicUtilService basicUtilService;
	
	@Resource(name = "logicUtilService")
	private ILogicUtilService logicUtilService;
	@Override
	public String manager(HttpServletRequest request, Model model)
			throws Exception {
		return MANAGER;
	}

	@Override
	public void list(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions payScs = new SearchConditions();
		hander.getWheres(payScs);
		//payScs.setRemovedProperty(null);
		String zdStatus = request.getParameter("zdStatus");
		if(StringUtils.isNotBlank(zdStatus)){
			payScs.addCondition("zd003Status", zdStatus, SearchCondition.OP_EQUAL);
		}
		String zdSupeId = request.getParameter("zdSupeId");
		if(StringUtils.isNotBlank(zdStatus)){
			payScs.addCondition("zd009SupeId", zdSupeId, SearchCondition.OP_EQUAL);
		}
		payScs.setOrderBy("bizCreatorDate desc");
		SearchResult result= logicPayReturnService.findListByExample(payScs);
		OutJsonGrid out=new OutJsonGrid(result);
		out.printJSon(response);
	}

	@Override
	public String operationForm(HttpServletRequest request, @PathVariable String id,
			@PathVariable String flag, Model model) throws Exception {
		if (OperationFlag.ADD.equals(flag)) {
			// 新增单据时操作
			model.addAttribute("flag", "ADD");
			//查询采购退货单
			SearchConditions whrScs = new SearchConditions();
			whrScs.setRemovedProperty(null);
			List<LogicPurchaseReturnDO> pcsrList = logicUtilService.resultPurchaseReturn(whrScs);
			model.addAttribute("pcsrList", pcsrList);
			//查询付款方式
			SearchConditions payScs = new SearchConditions();
			payScs.setRemovedProperty(null);
			List<BasicModePaymentTestDO> payments = basicUtilService.resultPayments(payScs);
			model.addAttribute("paysList", payments);
		} else {
			//修改单据时操作
			LogicPayReturnDO lpd = logicPayReturnService.findListById(id);
			model.addAttribute("payr", lpd);
		}
		return EIDT;
	}

	@Override
	public Map<String, Object> save(HttpServletRequest request,
			LogicPayReturnDO curAP, BindingResult result, Model model)
			throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		String itemdata =request.getParameter("itemdata");
		String flagMark = request.getParameter("flagMark");
		if(StringUtils.isBlank(itemdata)){
			bodyMap.isFail();
			bodyMap.configWebInfor("付款单内容不能为空！");
			return bodyMap.modelMap;
		}
		try {
			curAP.setZd003Status(flagMark);
			if(BillStatusUtil.PAYRN_BILL_STATUS_ONE.equals(flagMark)){
				//保存草稿
				logicPayReturnService.payReturnSave(curAP, request);
			}
			if(BillStatusUtil.PAYRN_BILL_STATUS_TWO.equals(flagMark)){
				//保存草稿
				logicPayReturnService.payReturnCommit(curAP, request);
			}
			bodyMap.isSuccess();
			bodyMap.configWebInfor(GlobalResLoader.getOpsuccess());
			bodyMap.configWebId(curAP.getId());
		} catch (Exception e) {
			e.printStackTrace();
			bodyMap.isFail();
			bodyMap.configWebInfor(GlobalResLoader.getOpfailed()+ e.getMessage());
		}
		return bodyMap.modelMap;
	}

	@Override
	public Map<String, Object> delete(HttpServletRequest request,
			HttpServletResponse response, Model model) throws Exception {
		BodyMsg bodyMap = BodyMsg.getInstance();
		try {
				String ids = request.getParameter("ids");
				String[] fields=ids.split(",");
				for(String field : fields){
					if(StringUtils.isBlank(field)){
						continue;
					}else{
						logicPayReturnService.deleteBizRemoved(field);
					}
				}
				bodyMap.isSuccess(GlobalResLoader.getOpsuccess());
			} catch (Exception e) {
				e.printStackTrace();
				bodyMap.isFail(GlobalResLoader.getOpfailed() + e.getMessage());
			}
			return bodyMap.modelMap;
	}

	/**
	 * 供应商列表
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value = "/tree")
	public void treelist(HttpServletRequest request,HttpServletResponse response)throws Exception{
		JqGridHandler hander=new JqGridHandler(request);
		SearchConditions scs = new SearchConditions();
		scs.setLimitPage(false);//不分页
		scs.setRemovedProperty(null);
		hander.getWheresNotLimit(scs);
		List<BasicCompanyTestDO> list =basicUtilService.resultCompany(scs);
		AjaxUtil.printJSonArr(response, JSONArray.toJSONString(list));
	}
	
	/**
	 * 查询付款退款item集合
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/girdItems")
	public void girdItems(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String payrId = request.getParameter("payrId");
		if(StringUtils.isNotBlank(payrId)){
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("payrId", payrId);
			List<LogicPayReturnItemDO> payrItemList = logicPayReturnService.findItemListByMap(paramMap);
			OutJsonGrid out = new OutJsonGrid(payrItemList);
			out.printJSon(response);
		}
	}
	
	/**
	 * 根据采购入库单id查询单据信息
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/pcsrQuary")
	@ResponseBody
	public LogicPayReturnDO pcsrQuary(HttpServletRequest request,Model model) throws Exception{
		LogicPayReturnDO payRnMoney = new LogicPayReturnDO();
		BigDecimal pcswSum = BigDecimal.ZERO;
		try{
			//采购订单ID
			String pcsId = request.getParameter("pcsId");
			LogicPurchaseDO pcs = logicPurchaseService.findListById(pcsId);
			if(pcs !=null ){
				payRnMoney.setZd010ExRateVal(pcs.getZd004Exchange());
				SearchConditions curScs = new SearchConditions();
				curScs.setRemovedProperty(null);
				curScs.addCondition("id", pcs.getZd003CurrencyId(), SearchCondition.OP_EQUAL);
				List<BasicCurrencyTestDO> curList = basicUtilService.resultCurrency(curScs);
				if(curList==null||curList.isEmpty()||curList.size()==0){
					payRnMoney.setZd010ExRateCode("");
					payRnMoney.setZd010ExRateName("");
				}else{
					payRnMoney.setZd010ExRateCode(curList.get(0).getZd002CurrencyCode());
					payRnMoney.setZd010ExRateName(curList.get(0).getZd001CurrencyName());
				}
			}
			//采购退货单ID,根据采购退货单查询item集合
			String pcsrId = request.getParameter("pcsrId");
			LogicPurchaseReturnDO pcsr = logicPurchaseReturnService.findListById(pcsrId);
			if(pcsr !=null){
				payRnMoney.setZd009SupeId(pcsr.getZd008SpId());
				payRnMoney.setZd009SupeCode(pcsr.getZd008SpCode());
				payRnMoney.setZd009SupeName(pcsr.getZd008SpName());
			}
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("pcsrId", pcsrId);
			List<LogicPurchaseReturnItemDO> pcsrItemList = logicPurchaseReturnItemService.findListByMap(paramMap);
			for(LogicPurchaseReturnItemDO pcsrItem : pcsrItemList){
				if(pcsrItem==null){
					continue;
				}
				BigDecimal taxprice = pcsrItem.getZd013TaxPrice()==null?BigDecimal.ZERO:pcsrItem.getZd013TaxPrice();
				BigDecimal zdQuantity = pcsrItem.getZd020BackQuantity()==null?BigDecimal.ZERO:pcsrItem.getZd020BackQuantity();
				pcswSum = pcswSum.add(taxprice.multiply(zdQuantity));
			}
			//赋值应退总金额
			payRnMoney.setZd004SumAmount(pcswSum);
			//已退款金额
			paramMap.put("zdStatus", BillStatusUtil.PAYRN_BILL_STATUS_TWO);
			BigDecimal lastSumMoney = logicPayReturnService.findQueryHasPayReturnMoney(paramMap);
			payRnMoney.setZd005HasAmount(lastSumMoney==null?BigDecimal.ZERO:lastSumMoney);
		}catch(Exception e){
			e.printStackTrace();
		}
		return payRnMoney;
	}
	
	/**
	 * 根据采购入库单的id查询采购入库单item集合
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/pcsrItemQuery")
	public void pcsrItemQuery(HttpServletRequest request,HttpServletResponse response) throws Exception{
		String pcsrId = request.getParameter("pcsrId");
		if(StringUtils.isNotBlank(pcsrId)){
			//查询采购退货单的item
			Map<String, Object> paramMap = new HashMap<String, Object>();
			paramMap.put("pcsrId", pcsrId);
			List<LogicPurchaseReturnItemDO> pcsrItemList = logicPurchaseReturnItemService.findListByMap(paramMap);
			if(pcsrItemList==null){
				pcsrItemList = new ArrayList<LogicPurchaseReturnItemDO>();
			}
			List<LogicPayReturnDO> payRnHisList = this.findPayRnListByScs(pcsrId);
			List<LogicPayReturnItemDO> payItemList = this.payRnItemListComp(pcsrItemList, payRnHisList);
			OutJsonGrid out = new OutJsonGrid(payItemList);
			out.printJSon(response);
		}
	}
	
	
	/**
	 * 根据
	 * @param pcswId
	 * @return
	 * @throws SyBaseException
	 */
	@SuppressWarnings("unchecked")
	private List<LogicPayReturnDO> findPayRnListByScs(String pcsrId)throws SyBaseException{
		SearchConditions payScs = new SearchConditions();
		payScs.setRemovedProperty(null);
		payScs.addCondition("zd002PcsrId", pcsrId, SearchCondition.OP_EQUAL);
		SearchResult paySrs = logicPayReturnService.findListByExample(payScs);
		return paySrs.getResults();
	}
	
	/**
	 * 组装付款单的item集合列表
	 * @param pcswItemList
	 * @param payHisList
	 * @return
	 */
	private List<LogicPayReturnItemDO> payRnItemListComp(List<LogicPurchaseReturnItemDO> pcsrItemList, List<LogicPayReturnDO> payRnHisList){
		List<LogicPayReturnItemDO> payRnItemList = new ArrayList<LogicPayReturnItemDO>();
		for(LogicPurchaseReturnItemDO pcsrItem : pcsrItemList){
			if(pcsrItem==null){
				continue;
			}
			LogicPayReturnItemDO payRnItem = new LogicPayReturnItemDO();
			payRnItem.setZd002MaterId(pcsrItem.getZd003MaterId());
			payRnItem.setZd003MaterCode(pcsrItem.getZd004MaterCode());
			payRnItem.setZd004MaterName(pcsrItem.getZd005MaterName());
			payRnItem.setZd005Type(pcsrItem.getZd006MaterType());
			payRnItem.setZd006Spec(pcsrItem.getZd007MaterSpec());
			payRnItem.setZd012Unit(pcsrItem.getZd016Unit());
			payRnItem.setZd013Price(pcsrItem.getZd014Price());
			//含税单价
			BigDecimal taxprice = pcsrItem.getZd013TaxPrice()==null?BigDecimal.ZERO:pcsrItem.getZd013TaxPrice();
			payRnItem.setZd013TaxPrice(taxprice);
			//退货数量
			BigDecimal zdQuantity = pcsrItem.getZd020BackQuantity()==null?BigDecimal.ZERO:pcsrItem.getZd020BackQuantity();
			payRnItem.setZd020Quantity(zdQuantity);
			//赋值应退总金额
			BigDecimal zdSumMoney = taxprice.multiply(zdQuantity);
			payRnItem.setZd016Amount(zdSumMoney);
			if(payRnHisList==null || payRnHisList.isEmpty() || payRnHisList.size()==0){
				//没有历史的退款记录
				payRnItem.setZd019NoAmount(zdSumMoney);
				payRnItem.setZd017HasAmount(BigDecimal.ZERO);
			}else{
				//存在历史的退款记录
				BigDecimal tempHsMoney = BigDecimal.ZERO;
				BigDecimal zdHsMoney = BigDecimal.ZERO;
				BigDecimal zdNoMoney = BigDecimal.ZERO;
				for(LogicPayReturnDO payRnHis : payRnHisList){
					if(payRnHis==null || StringUtils.isBlank(payRnHis.getId())){
						continue;
					}
					//查询物料的历史退款记录
					Map<String, Object> payItemMap = new HashMap<String, Object>();
					payItemMap.put("payRnId", payRnHis.getId());
					payItemMap.put("materId", pcsrItem.getZd003MaterId());
					List<LogicPayReturnItemDO> _payItemList = logicPayReturnService.findItemListByMap(payItemMap); 
					if(_payItemList==null || _payItemList.isEmpty() || _payItemList.size()==0){
						continue;
					}else{
						BigDecimal pzdThMoney = _payItemList.get(0).getZd018TheAmount()==null?BigDecimal.ZERO:_payItemList.get(0).getZd018TheAmount();
						tempHsMoney = tempHsMoney.add(pzdThMoney);
						//未付款
						zdNoMoney = zdSumMoney.subtract(tempHsMoney);
						//付款
						zdHsMoney = zdHsMoney.add(pzdThMoney);
					}
				}
				payRnItem.setZd019NoAmount(zdNoMoney);
				payRnItem.setZd017HasAmount(zdHsMoney);
			}
			payRnItemList.add(payRnItem);
		}
		return payRnItemList;
	}
}
